package com.jzbwlkj.windowmanager.service;

import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jzbwlkj.windowmanager.MainActivity;
import com.jzbwlkj.windowmanager.R;

import java.util.List;
import java.util.Random;

public class WindowService extends Service
{
    private WindowManager mWindowManager;
    private WindowManager.LayoutParams mParams;
    private View mWindowView;
    public ImageView mImgView;

    private float mStartX;
    private float mStartY;
    private float mEndX;
    private float mEndY;

    public boolean 是否贴屏 = true;
    private Intent reIntent = new Intent("com.example.communication.RECEIVER");

    @Override
    public void onCreate()
    {
        super.onCreate();
        initView();
        setWindowParams();
        addView();
        initClick();

    }

    /**
     * WindowManager添加View
     */
    private void addView()
    {
        mWindowManager.addView(mWindowView, mParams);
    }

    /**
     * 设置LayoutParams
     */
    private void setWindowParams()
    {
        //TYPE_APPLICATION 本应用内


        mParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
                | WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;

        mParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;

        mParams.format = PixelFormat.TRANSLUCENT;

        mParams.gravity = Gravity.TOP | Gravity.LEFT;
        mParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        mParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        mParams.x = (mWindowManager.getDefaultDisplay().getWidth() - mWindowView.getWidth());
        mParams.y = (mWindowManager.getDefaultDisplay().getHeight() / 2);
    }

    /**
     * 初始化View
     */
    private void initView()
    {
        //注意使用TYPE_PHONE时，要用MainActivity.this
        mWindowManager = (WindowManager) getApplication().getSystemService(WINDOW_SERVICE);
        mParams = new WindowManager.LayoutParams();
        mWindowView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.view_window,
                null);
        mImgView = (ImageView) mWindowView.findViewById(R.id.tv_message_toast);

        //mImgView.setText("我是悬浮窗");
    }

    public WindowService()
    {
    }


    /**
     * 返回一个Binder对象
     */
    @Override
    public IBinder onBind(Intent intent)
    {
        return new MsgBinder();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        if (mWindowManager != null)
        {
            //移除悬浮窗口
            mWindowManager.removeView(mWindowView);
        }
    }

    private void initClick()
    {
        mImgView.setOnTouchListener(new View.OnTouchListener()
        {

            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                Boolean x;
                if (是否贴屏)
                {
                    x = getTouchWay2(event);

                } else
                {
                    x = getTouchWay1(event);
                }
                if (x != null) return x;
                return false;
            }

            @Nullable
            private Boolean getTouchWay1(MotionEvent event)
            {
                switch (event.getAction())
                {
                    case MotionEvent.ACTION_DOWN:
                        mStartX = event.getRawX();
                        mStartY = event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        mEndX = event.getRawX();
                        mEndY = event.getRawY();
                        if (needIntercept())
                        {
                            //getRawX是触摸位置相对于屏幕的坐标，getX是相对于按钮的坐标
                            mParams.x = (int) event.getRawX() - mWindowView.getMeasuredWidth() / 2;
                            //减25为状态栏的高度
                            mParams.y = (int) event.getRawY() - mWindowView.getMeasuredHeight
                                    () / 2 - 25;


//                            mImgView = (TextView) mWindowView.findViewById(R.id.tv_message_toast);
//                            mImgView.setText("我是悬浮窗" + new Random().nextInt(100));
//
//
                            mWindowManager.updateViewLayout(mWindowView, mParams);
                            return true;
                        }


                        break;
                    case MotionEvent.ACTION_UP:
                        if (needIntercept())
                        {
                            return true;
                        }
                        break;
                    default:
                        break;
                }
                return null;
            }

            private Boolean getTouchWay2(MotionEvent event)
            {
                switch (event.getAction())
                {
                    case MotionEvent.ACTION_DOWN:
                        mStartX = event.getRawX();
                        mStartY = event.getRawY();

                        mEndX = event.getRawX();
                        mEndY = event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        float x = event.getRawX() - mStartX;
                        float y = event.getRawY() - mStartY;
                        //计算偏移量，刷新视图
                        mParams.x += x;
                        mParams.y += y;

                        mWindowManager.updateViewLayout(mWindowView, mParams);
                        mStartX = event.getRawX();
                        mStartY = event.getRawY();
                        break;
                    case MotionEvent.ACTION_UP:
                        //判断松手时View的横坐标是靠近屏幕哪一侧，将View移动到依靠屏幕
                        float endX = event.getRawX();
                        float endY = event.getRawY();
                        if (endX < mWindowManager.getDefaultDisplay().getWidth() / 2)
                        {
                            endX = 0;
                        } else
                        {
                            endX = mWindowManager.getDefaultDisplay().getWidth() - mWindowView
                                    .getWidth();
                        }
                        mParams.x = (int) endX;
                        mWindowManager.updateViewLayout(mWindowView, mParams);
                        //如果初始落点与松手落点的坐标差值超过6个像素，则拦截该点击事件
                        //否则继续传递，将事件交给OnClickListener函数处理
                        if (Math.abs(endX - mEndX) > 6 && Math.abs(endY - mEndY) > 6)
                        {
                            return true;
                        }
                        break;
                }
                return null;
            }
        });


        mImgView.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                Toast.makeText(WindowService.this, "发送广播", Toast.LENGTH_SHORT).show();
                //发送Action为com.example.communication.RECEIVER的广播
                //reIntent.putExtra("progress", "0");

                sendBroadcast(reIntent);
            }
        });
    }

    /**
     * 是否拦截
     *
     * @return true:拦截;false:不拦截.
     */
    private boolean needIntercept()
    {
        if (Math.abs(mStartX - mEndX) > 30 || Math.abs(mStartY - mEndY) > 30)
        {
            return true;
        }
        return false;
    }

    /**
     * 判断当前应用程序处于前台还是后台
     */
    private boolean isAppAtBackground(final Context context)
    {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty())
        {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName()))
            {
                mWindowManager.removeView(mWindowView);
                return true;
            }
        } else
        {
            mWindowManager.addView(mWindowView, mParams);
        }
        return false;
    }

    public class MsgBinder extends Binder
    {
        /**
         * 获取当前Service的实例
         *
         * @return
         */
        public WindowService getService()
        {
            return WindowService.this;
        }
    }
}
